//
//  AUSharedModule.swift
//  AwesomeUSharedModule_Example
//
//  Created by Miss_Special on 2018/4/11.
//  Copyright © 2018 CocoaPods. All rights reserved.
//

public struct AUSharedModule {
    
    public static let sharedInstance: AUSharedModule = AUSharedModule()
    
    private init() { }
    
    /**
     ******************** scheme中不能有下划线 ********************
     -> scheme://host/path?query
     -> [moduleName]://[targetName]/[actionName]?[params]
     
     example:
     -> moduleA://targetA/actionA?id=1&name="hhh"
     
     - Parameters:
      - url: 配置url
      - bundle: 调用的module所在的bundle
      - completion: 完成回调
     */
    func au_performActionWithUrl(url: URL, completion: (() -> ())?) {
        
        // 处理参数
        var params: [String: Any] = [:]
        if let urlString = url.query {
            for param in urlString.components(separatedBy: "&") {
                let elements = param.components(separatedBy: "=")
                if elements.count < 2 { continue }
                if let key = elements.first, let value = elements.last {
                    params[key] = value
                }
            }
        }
        
        // target-action
        let actionName = url.path.replacingOccurrences(of: "/", with: "")
        let action = Selector(("\(actionName)"))
        
        // 得到当前Bundle名
//        guard let nameSpace = bundle.object(forInfoDictionaryKey: "CFBundleExecutable") as? String else {
//            return
//        }
        guard let nameSpace = url.scheme else {
            print("Scheme不合法")
            return
        }
        
        guard let targetName = url.host else {
            return
        }
        if let targetClass = NSClassFromString("\(nameSpace).\(targetName)") as? NSObject.Type {
            let target = targetClass.init()
            
            if target.responds(to: action) {
                target.perform(action, with: params)
                completion?()
            } else {
                print("没有找到Action: \(actionName)")
            }
        } else {
            print("没有找到Class: \(nameSpace).\(targetName)")
        }
    }
}
